import Link from 'next/link';
import { useEffect } from 'react';
import moment from 'moment';
import { Checkbox, InputNumber, message, Popconfirm } from 'antd';
import { connect } from "react-redux";
import { totalDays, targetUrl, replaceImageUrl, formatNumTo2, formatActicityType } from '@/utils';
import { getCartListData, modifyCartListData, allCheckCartListData } from '@/store/actions/cart';
import { addCartLimit } from '../format_js';
// css
import styles from '@/styles/ShoppingCart.module.scss';
// api
import { reduceOrAddGoodsToCart, removeGoodsFromCart } from '@/api/cart';

let timer = null;

// item component
const Item = ({ data, setData, _getCartListData, _allCheckCartListData, _modifyCartListData }) => {
    const { userCanUseCouponDTOList, startDate, endDate, amount, salePrice } = data;
    const { minNum, maxNum } = addCartLimit(data);
    const today = moment(new Date()).format('YYYY-MM-DD');
    const isHotel = startDate !== endDate;
    const isOutDate = new Date(today) > new Date(startDate);
    // 选中
    const checkboxFn = (checked) => {
        data.checked = checked;
        setData(data);
    }
    // 改变数量
    const changeNumFn = (value) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            data.amount = value;
            reduceOrAddGoodsToCart({ id: data.id, number: value }).then(res => {
                const { code } = res;
                if(code == 0){
                    _getCartListData();
                    _modifyCartListData();
                    _allCheckCartListData(false);
                }
            });
            setData(data);
        }, 500);
    }
    // 删除
    const removeItem = (data) => {
        removeGoodsFromCart(data.id).then(res => {
            const { code } = res;
            if(code === 0){
                message.success('已删除');
                _getCartListData();
                _allCheckCartListData(false);
                _modifyCartListData();
            }
        })
    }

    const href = targetUrl(data);

    return (
        <div className={[styles['tr'], isOutDate && styles['outdate']].join(' ')}>
            <div className={styles['check']}>
                <Checkbox checked={data.checked} disabled={isOutDate} onChange={(e) => { checkboxFn(e.target.checked) }} />
            </div>
            <div className={styles['product']}>
                <Link href={href}>
                    <a target="_blank">
                        <img src={replaceImageUrl(data.img)} alt="" />
                    </a>
                </Link>
                <div className={styles['product-info']}>
                    <Link href={href}><a target="_blank">{data.goodsName}</a></Link>
                    <p>
                        <span>{data.goodsExtendName}</span>
                    </p>
                    {
                        data.specificationsInfo
                        ? <p>{JSON.parse(data.specificationsInfo).area} | {JSON.parse(data.specificationsInfo).time} | {JSON.parse(data.specificationsInfo).ticketType}</p>
                        : null
                    }
                </div>
            </div>
            <div className={styles['usedate']}>
                {
                    isHotel
                    ? <div>
                        <p><span>{startDate}</span> 入住</p>
                        <p><span>{endDate}</span> 退房</p>
                        <span>共{totalDays(startDate, endDate)}晚</span>
                    </div>
                    : <p><span>{startDate}</span></p>
                }
            </div>
            <div className={styles['price']}>
                {
                    userCanUseCouponDTOList.length
                    ? <div>
                        <p>¥ <span>{salePrice}</span></p>
                        <em>优惠券</em>
                    </div>
                    : <p>¥ <span>{salePrice}</span></p>
                }
            </div>
            <div className={styles['number']}>
                <InputNumber min={minNum} max={maxNum} value={amount} disabled={isOutDate} onChange={v => { changeNumFn(v) }} />
            </div>
            <div className={styles['total']}>
                {
                    data.projectId == 3 
                    ? <p>¥ <span>{formatNumTo2(amount*salePrice*totalDays(startDate, endDate))}</span></p>
                    : <p>¥ <span>{formatNumTo2(amount*salePrice)}</span></p>
                }
            </div>
            <div className={styles['operate']}>
                <Popconfirm
                    placement="left"
                    title="确认删除该商品吗？"
                    okText="确认"
                    cancelText="取消"
                    onConfirm={() => { removeItem(data) }}
                ><span>删除</span></Popconfirm>
            </div>
        </div>
    )
}

// part component
const PartItem = ({ data, setData, _getCartListData, _allCheckCartListData, _modifyCartListData }) => {
    // algorithms  1 早定优惠 2 特价直减 3 满减优惠
    const { activityName, algorithms, title, goodsCartActivityListDTO } = data;
    const Title = algorithms ? (
        <div className={styles['thead']}>
            <span>{formatActicityType(algorithms)}</span>
            <span>{activityName}</span>
            <span>【{title}】</span>
        </div>
    ) : ""
    return (
        <div className={styles['part']}>
            { Title }
            {
                !!goodsCartActivityListDTO?.length &&
                goodsCartActivityListDTO.map(item => {
                    return <Item key={item.id} 
                                 data={item} 
                                 setData={setData} 
                                 _getCartListData={_getCartListData} 
                                 _allCheckCartListData={_allCheckCartListData}
                                 _modifyCartListData={_modifyCartListData}
                            />
                })
            }
        </div>
    )
}

const CartList = ({ _getCartListData, _modifyCartListData, _allCheckCartListData, cart: { cartList } }) => {

    useEffect(() => {
        return function (){
            cartList.forEach(data => {
                const { goodsCartActivityListDTO } = data;
                goodsCartActivityListDTO.forEach(g => {
                    g.checked = false;
                })
            });
            _modifyCartListData(cartList);
            _allCheckCartListData(false);
        }
    }, []);

    // 更新数据
    const setData = (item) => {
        let checkedNum = 0,
            listLength = 0;
        cartList.forEach(data => {
            const { goodsCartActivityListDTO } = data;
            goodsCartActivityListDTO.forEach(g => {
                if(g.id === item.id){
                    g.checked = item.checked;
                }
                // 取消全选
                if(!item.checked){
                    _allCheckCartListData(item.checked);
                }
                if(g.checked){
                    checkedNum ++;
                }
                listLength ++;
            })
        });
        _modifyCartListData(cartList);
        _allCheckCartListData(listLength === checkedNum);
    }
    return (
        <div className={styles['table-body']}>
            {
                cartList.map((item, index) => {
                    const { activityBaseId } = item;
                    const key = activityBaseId ? activityBaseId : '0'+index;
                    return <PartItem key={key} 
                                     data={item} 
                                     setData={setData} 
                                     _getCartListData={_getCartListData} 
                                     _allCheckCartListData={_allCheckCartListData}
                                     _modifyCartListData={_modifyCartListData}
                            />
                })
            }
        </div>
    )
}

const mapStateToProps = state => {
    return {
        cart: state.cart
    }
}
const mapDispatchToProps = dispatch => {
    return {
        _getCartListData: v => dispatch(getCartListData(v)),
        _modifyCartListData: v => dispatch(modifyCartListData(v)),
        _allCheckCartListData: v => dispatch(allCheckCartListData(v)),
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(CartList);
